package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsGoodsMapper;
import com.qf.pojo.*;
import com.qf.service.*;
import com.qf.util.ResponseUtil;
import com.qf.vo.GoodsAllinone;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
@Service
public class DtsGoodsServiceImpl implements DtsGoodsService {

    @Autowired
    DtsGoodsMapper goodsMapper;

    @Autowired
    DtsBrandService brandService;

    @Autowired
    DtsCategoryService categoryService;

    @Autowired
    DtsGoodsAttributeService attributeService;

    @Autowired
    DtsGoodsSpecificationService specificationService;

    @Autowired
    DtsGoodsProductService productService;

    @Override
    public int queryTotal() {

        LambdaQueryWrapper<DtsGoods> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtsGoods::getDeleted, false);

        Integer count = goodsMapper.selectCount(wrapper);
        return count;
    }

    @Override
    public IPage<DtsGoods> queryPage(Integer page, Integer limit, String goodsSn, String name, String sort, String order, List<Integer> brandIds) {

        IPage<DtsGoods> ipage = new Page<>(page, limit);

        QueryWrapper wrapper = new QueryWrapper();

        if(!StringUtils.isEmpty(goodsSn)){
            wrapper.like("goods_sn", goodsSn);
        }

        if(!StringUtils.isEmpty(name)){
            wrapper.like("name", name);
        }

        if(brandIds != null && brandIds.size() > 0 ){
            wrapper.in("brand_id", brandIds);
        }

        if(!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order) ){
            if(order.equals("desc")){
                wrapper.orderByDesc(sort);
            }else{
                wrapper.orderByAsc(sort);
            }
        }



        goodsMapper.selectPage(ipage, wrapper);
        return ipage;
    }

    @Override
    public DtsGoods findById(Integer id) {
        return goodsMapper.selectById(id);
    }


    public Object validate(GoodsAllinone goodsAllinone){
        if(goodsAllinone == null){
            return ResponseUtil.badArgument();
        }
        //获取商品对象
        DtsGoods goods = goodsAllinone.getGoods();
        if(StringUtils.isEmpty(goods.getName())){
            return ResponseUtil.badArgument();
        }
        if(StringUtils.isEmpty(goods.getGoodsSn())){
            return ResponseUtil.badArgument();
        }

        //获取品牌商id
        Integer brandId = goods.getBrandId();
        if(brandId != null){
            if(brandService.findById(brandId) == null){
                return ResponseUtil.badArgument();
            }
        }

        Integer categoryId = goods.getCategoryId();
        if(categoryId != null){
            if(categoryService.findById(categoryId) == null){
                return ResponseUtil.badArgument();
            }
        }

        //获取商品的属性
        DtsGoodsAttribute[] attributes = goodsAllinone.getAttributes();
        if(attributes != null && attributes.length > 0){
            for (DtsGoodsAttribute attribute : attributes) {
                if(attribute.getAttribute() == null || attribute.getValue() == null)
                {
                    return ResponseUtil.badArgument();
                }
            }
        }

        //获取商品的规格
        DtsGoodsSpecification[] specifications = goodsAllinone.getSpecifications();
        if(specifications != null && specifications.length > 0){
            for (DtsGoodsSpecification specification: specifications) {
                if(specification.getSpecification() == null || specification.getValue() == null)
                {
                    return ResponseUtil.badArgument();
                }
            }
        }

        //获取库存
        DtsGoodsProduct[] products = goodsAllinone.getProducts();
        if(products != null && products.length > 0){
            for (DtsGoodsProduct product: products) {
                if(product.getNumber() == null || product.getPrice() == null)
                {
                    return ResponseUtil.badArgument();
                }
            }
        }

        return null;
    }

    @Override
    public Object update(GoodsAllinone goodsAllinone) {
        Object result = this.validate(goodsAllinone);
        if(result != null){
            return result;
        }

        DtsGoods goods = goodsAllinone.getGoods();
        //开始更新数据库
        //1. 更新商品表
        goods.setUpdateTime(new Date());
        goodsMapper.updateById(goods);
        //2. 更新属性表
        DtsGoodsAttribute[] attributes = goodsAllinone.getAttributes();
        //2.1 删除此商品所有相关属性
        attributeService.deleteByGoodsId(goods.getId());
        //2.2 添加新的商品属性
        if(attributes != null && attributes.length > 0){
            for (DtsGoodsAttribute attribute : attributes) {
                attribute.setGoodsId(goods.getId());

                attributeService.insert(attribute);
            }
        }

        //3. 更新规格表
        //3.1 删除此商品所有相关规格
        specificationService.deleteByGoodsId(goods.getId());
        //3.2 添加新的商品规格
        DtsGoodsSpecification[] specifications = goodsAllinone.getSpecifications();
        if(specifications != null && specifications.length > 0){
            for (DtsGoodsSpecification specification : specifications) {
                specification.setGoodsId(goods.getId());
                specification.setAddTime(new Date());
                specification.setUpdateTime(new Date());
                specification.setDeleted(false);
                specificationService.insert(specification);
            }
        }

        //4. 更新库存表
        //4.1 删除此商品所有相关库存
        productService.deleteByGoodsId(goods.getId());
        //4.2 添加新的商品库存
        DtsGoodsProduct[] products = goodsAllinone.getProducts();
        if(products != null && products.length > 0){
            for (DtsGoodsProduct product : products) {
                product.setGoodsId(goods.getId());
                product.setAddTime(new Date());
                product.setUpdateTime(new Date());
                product.setDeleted(false);
                productService.insert(product);
            }
        }



        return ResponseUtil.ok();
    }

    @Autowired
    DtsOrderGoodsService orderGoodsService;

    @Override
    public Object deleteById(Integer id) {
        List<DtsOrderGoods> ordergoods = orderGoodsService.findByGoodsId(id);
        //1. 判断商品是否被订单关联，如果关联不能删除
        if(ordergoods != null && ordergoods.size() > 0) {
            return ResponseUtil.unsupport();
        }

        //2. 删除商品对应属性
        attributeService.deleteByGoodsId(id);
        //3. 删除商品对应库存
        productService.deleteByGoodsId(id);
        //4. 删除商品对应规格
        specificationService.deleteByGoodsId(id);
        //5. 删除商品
        goodsMapper.deleteById(id);

        return ResponseUtil.ok();
    }

    @Override
    public Object create(GoodsAllinone goodsAllinone) {
        Object result = validate(goodsAllinone);
        if(result != null){
            return result;
        }

        DtsGoods goods = goodsAllinone.getGoods();
        //新增 商品 // goods.id 是 新增商品后 自动回显主键(mybatis-plus )
        //判断商品名称是否重复
        goodsMapper.insert(goods);

        //新增 商品属性
        DtsGoodsAttribute[] attributes = goodsAllinone.getAttributes();
        if(attributes != null && attributes.length > 0){
            for (DtsGoodsAttribute attribute : attributes) {
                attribute.setGoodsId(goods.getId());
                attribute.setDeleted(false);
                attribute.setAddTime(new Date());
                attribute.setUpdateTime(new Date());
                attributeService.insert(attribute);
            }
        }

        //新增 商品规格
        DtsGoodsSpecification[] specifications = goodsAllinone.getSpecifications();
        if(specifications != null && specifications.length > 0){
            for (DtsGoodsSpecification specification : specifications) {
                specification.setGoodsId(goods.getId());
                specification.setDeleted(false);
                specification.setAddTime(new Date());
                specification.setUpdateTime(new Date());
                specificationService.insert(specification);
            }
        }
        //新增 商品库存
        DtsGoodsProduct[] products = goodsAllinone.getProducts();
        if(products != null && products.length > 0){
            for (DtsGoodsProduct product: products) {
                product.setGoodsId(goods.getId());
                product.setDeleted(false);
                product.setAddTime(new Date());
                product.setUpdateTime(new Date());
                productService.insert(product);
            }
        }

        return ResponseUtil.ok();
    }
}
